package com.example.world.dao;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.example.world.domain.City;

import com.example.world.utils.JDBCUtils;

public class CityDAO {


	// 根据code查询国家
	public City findByCode(String name, String countrycode,String district) throws SQLException
	{
		// 1. 连接 
		Connection conn = JDBCUtils.getConnection();
		// 2. 
		String sql = "select * from city where CountryCode=?";
		PreparedStatement stmt = conn.prepareStatement(sql);
		stmt.setString(1, countrycode);
		// 3. 
		ResultSet rs = stmt.executeQuery();
		City c = null;
	
		if(rs.next())
		{
			String name1 = rs.getString("Name");
			String district1= rs.getString("district");
			c = new City(name1,countrycode,district1);
		}
				
		return c;
	}
	
	// 查询所有
	public List<City> findAll() throws SQLException
	{
		// 1. 连接
		Connection conn = JDBCUtils.getConnection();
		// 2.
		String sql = "select * from city";
		PreparedStatement stmt = conn.prepareStatement(sql);
		// 3.
		ResultSet rs = stmt.executeQuery();
		List<City> list = new ArrayList<>();
		while (rs.next()) 
		{
			String name = rs.getString("Name");
			String countrycode = rs.getString("CountryCode");
			String district = rs.getString("District");
			City c = new City( name, countrycode,district);
			list.add(c);
		}

		return list;
	}
}